var LoginControl = require("../../../control/LoginControl");
var RoomControl = require("../../../control/RoomControl");
var AccountControl = require("../../../control/AccountControl");
module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
};
// 登录
Handler.prototype.login = function(msg, session, next) {
    LoginControl.login(this.app, msg.username, (err, result)=>{
        if (err) {
            next(null, {ret:-1});
        } else {
            session.on('closed', onUserLeave.bind(null, this.app));

            session.bind(result._id, ()=>{
                this.app.rpc.chat.chatRemote.enterChannel(session, session.uid, this.app.get("serverId"), ()=>{
                    next(null, {ret: 0, data:{model:[{key:"model.account", value:result}]}});
                });
            });
        }
    });
};
// 进入房间
Handler.prototype.enterRoom = function(msg, session, next) {
    this.app.rpc.dispatcher.dispatcherRemote.dispatch(session, session.uid, (roomId)=>{
        session.set("roomId", roomId);
        session.push("roomId", (err)=>{
            console.log(err);
            this.app.rpc.room.roomRemote.enterRoom(session, session.uid, roomId, this.app.get("serverId"), (roomModel)=>{
                next(null, {ret: 0, data:{model:[{key:"model.room", value:roomModel}]}});
            });
        });
	});
};
// 退出房间
Handler.prototype.exitRoom = function(msg, session, next) {
    this.app.rpc.dispatcher.dispatcherRemote.dispatch(session, session.uid, ()=>{
        this.app.rpc.room.roomRemote.exitRoom(session, session.uid, session.get('roomId'), this.app.get('serverId'), ()=>{
            next(null, {ret:0, data:{model:[{key:"model.room"}]}});
        });
	});
};

// 修改昵称
Handler.prototype.rename = function(msg, session, next) {
    AccountControl.rename(this.app, session.uid, msg.nickname, (err, result)=>{
        if (err) {
            next(null, {ret:-1});
        } else {
            next(null, {ret: 0, data:{model:[{key:"model.account.nickname", value:msg.nickname}]}});
        }
    });
};

/**
 * User log out handler
 *
 * @param {Object} app current application
 * @param {Object} session current session object
 *
 */
var onUserLeave = function(app, session) {
    console.log("onUserLeave", session.get("roomId"));
    app.rpc.chat.chatRemote.exitChannel(session, session.uid, app.get('serverId'), null);
	if(!session || !session.uid || !session.get("roomId")) {
		return;
	}
	app.rpc.room.roomRemote.exitRoom(session, session.uid, session.get('roomId'), app.get('serverId'), null);
};